Day 8: Working with Bash Scripts

Shell Environment

Interaction with the OS

When you execute a script, you spawn a new session (child process) of the current shell.

Scripts

First line declares the interpreter:
#!/bin/python
#!/bin/perl
#!/bin/bash

Variables

Declaration:
var='value'

Calling a variable:
echo $var

Shell Variable
VAR="my variable"
echo $VAR


Environment Variables

Variables passed onto child shell processes

export = Make variables available to the environment (sub shells)

env -u = remove variables from environment
env = print environmental variables

PATH=$PATH:/opt = Take original path and append :/opt to it. Adding :/opt to the PATH.

HISTFILESIZE = Set number of lines that history file remembers

alias myalis="echo 'whatever the fuck I want'"

. ./path_to_file = Read path_to_file into current shell


Bash Scripting

read VAR = Take input from user

ARRAY=() - Declare an empty array

expr $((2*30)) = Execute a mathematical expression

Easiest way to do a comparison = Use double brackets [[ ]]

if [[testing]]
then "Do something"
else "Do something else"
fi
if [[testing]]
then "Do something"
else "Do something else"
fi

Comparison Operators:
== or -eq
!= or -ne
>= or -ge
<= or -le
> or -gt
< or lt

Functions

func_name(val1 val2 val3){
code
code
code
code
}
func_name(val1 val2 val3){
code
code
code
code
}

the function parameters will be passed as $1(val1), $2(val2), $3(val3)


Metacharacters

$ = Call variable or end of line
^ = Begining of line
|| = OR
&& = AND
* = Wildcard matching anything
? = Matching a single character
[ ] = Matching characters between brackets
{ } = Parameter subsitituon and arrays
( ) = Grouping
: = Separate multiple commands on same line

Exit Codes
0 = Successful execution
1 or Higher = Error during execution

echo $? = Display exit code of last run command

case = better way to do an elif statement


For Loops

for var in $(something)
do 	something
    something
    something
done
for var in $(something)
do 	something
    something
    something
done

while and until loops start with:
do
and end in:
done